<?php
class Delivery_Model_Mapper_Administradores
	extends Delivery_Model_Mapper_Abstract
{
	/**
	 * @return object Zend_Db_Table
	 */
	public function getDbTable()
	{
		return parent::getDbTable( 'Administradores' );
	}
	
	/**
	 * @param object Delivery_Model_Administrador
	 */
	public function save( $administrador ){
		
		$dbTable = $this->getDbTAble();
		
		if ( $administrador->getId() == null ){
		   
			$administrador->setClave( $administrador->clave );
			
			$administrador->idAdministrador = $dbTable->insert( $administrador );
			
			return $this->idAdministrador;
		
		} else {
			
			return $dbTable->update( $administrador );
			
		}
	}
	
	/**
	 * @param object Delivery_Model_Administrador
	 */
	public function delete( $administrador ){
	
		$dbTable = $this->getDbTAble();
		
		$this->logDeleted( $administrador );
		
		return $dbTable->delete( $administrador );
	}
	
	
	/**
	 * @param int idAdministrador
	 * @return object Delivery_Model_Administrador
	 */
	public function getById( $idAdministrador ){
		
		if ( $this->getIdentityMap()->isRegistered( 'Delivery_Model_Administrador', $idAdministrador )){
			return $this->getIdentityMap()->get( 'Delivery_Model_Administrador', $idAdministrador );
		}
		
		$dbTable = $this->getDbTable();
		$rowset = $dbTable->getById( $idAdministrador );
		
		if( empty($rowset) ){
			throw new Delivery_Model_Exception('El usuario no existe');
		}
		
		return $this->_fetch( $rowset );		
	}

	/**
	 * @param string $email
	 * @param string $clave
	 * @return object Delivery_Model_Administrador
	 */
	public function login ( $email, $clave){
	
		$dbTable = $this->getDbTable();
				
		$clave = Delivery_Model_Administrador::clave( $clave );
		
		$row = $dbTable->getByAccount( $email, $clave );
		
		if( empty($row) ){
			throw new Delivery_Model_Exception( Delivery_Model_Exception::ADMIN_LOGIN_FAILED );
		}
		
		return $this->_fetch( $row );
	} 
	
	/**
	 * @param array
	 * @param int $offset
	 * @param int $limit
	 * @param string $order
	 * @return object Delivery_Model_Collection_Administradores
	 */
	public function getByParams( $params, $offset = null, $limit = null, $order = null ){
		
		$dbTable = $this->getDbTable();
			
		return $this->_fetchCollection(
			'Administradores',
			$dbTable->getByParams($params, $offset, $limit, $order)
		);
	}
	
	/**
	 * @param array
	 * @return int
	 */
	public function countByParams( $params ){
		return $this->getDbTable()->countByParams($params);
	}
	
	/**
	 * @param array
	 * @return object Delivery_Model_Administrador
	 */
	protected function _fetch( $row )
	{
		$administrador = new Delivery_Model_Administrador( $row );
		
		$this->getIdentityMap()->set( $administrador, $administrador->getId() );
		
		return $administrador;
	}
	
}